package com.site.user.controller;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.site.data.QueryResult;
import com.site.user.pojo.TbGroup;
import com.site.user.pojo.TbRole;
import com.site.user.pojo.TbUser;
import com.site.user.service.ITbGroupService;

@Controller
@RequestMapping("/group")
public class TbGroupController extends BaseController {
	@Resource
	private ITbGroupService tbGroupService;

	/**
	 * 查询数据列表
	 * @param request
	 * @param response
	 * @param out
	 */
	@RequestMapping(value = "/ser_save", method = RequestMethod.POST)
	public void save(HttpServletRequest request, HttpServletResponse response, PrintWriter out, TbGroup entity) {
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Expires", "0");
		response.setHeader("Content-Type", "text/html;charset=utf-8");
		String msg = "";
		String id = UUID.randomUUID().toString().replace("-", "");
		entity.setIdGroup(id);
		entity.setSign("1");
		entity.setCreatedTime(new Date());
		TbUser user = GetLoginSession(request, response);
		if (null != user) {
			entity.setCreatedUser(user.getUserName());
			tbGroupService.execSave(entity);
			msg = "保存成功.";
		} else {
			msg = "会话过期,请点击右上角的注销重新登录.";
		}
		out.println(msg);
	}

	/**
	 * 查询数据
	 * @param request
	 * @param response
	 * @param out
	 */
	@RequestMapping(value = "/ser_search", method = RequestMethod.POST)
	public void search(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Expires", "0");
		response.setHeader("Content-Type", "text/html;charset=utf-8");

		String whereJPQL = "1=1";

		Map mpparam = new HashMap();

		String groupName = ServletRequestUtils.getStringParameter(request, "groupName", "");
		if (StringUtils.isNotEmpty(groupName)) {
			whereJPQL += " and groupName like :groupName";
			mpparam.put("groupName", "%" + groupName + "%");
		}
		
		String groupType = ServletRequestUtils.getStringParameter(request, "groupType", "");
		if (StringUtils.isNotEmpty(groupType)) {
			whereJPQL += " and groupType=:groupType";
			mpparam.put("groupType",groupType);
		}
		
		String createUser = ServletRequestUtils.getStringParameter(request, "createUser", "");
		if (StringUtils.isNotEmpty(createUser)) {
			whereJPQL += " and createdUser like :createdUser";
			mpparam.put("createdUser", "%" + createUser + "%");
		}
		String outtimeStart = ServletRequestUtils.getStringParameter(request, "timeStart", "");
		String outtimeEnd = ServletRequestUtils.getStringParameter(request, "timeEnd", "");
		
		if ((StringUtils.isNotEmpty(outtimeStart))&&(StringUtils.isNotEmpty(outtimeEnd))){
			whereJPQL += " and createdTime  between '"+outtimeStart+"' AND '"+outtimeEnd+"'";
		
		}

		LinkedHashMap<String, String> orderby = new LinkedHashMap<String, String>();
		orderby.put("createdTime", "DESC");

		int pagesize = ServletRequestUtils.getIntParameter(request, "pagesize", 10);
		int page = ServletRequestUtils.getIntParameter(request, "page", 1);
		int maxResult = pagesize * page;
		int startIndex = pagesize * (page - 1);

		QueryResult result = tbGroupService.queryData(startIndex, maxResult, whereJPQL, mpparam, orderby);

		out.println(result.getResult("json"));

	}

	/**
	 * 载入数据
	 * @param request
	 * @param response
	 * @param out
	 */

	@RequestMapping(value = "/ser_load", method = RequestMethod.GET)
	public void load(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Expires", "0");
		response.setHeader("Content-Type", "text/html;charset=utf-8");

		String id = ServletRequestUtils.getStringParameter(request, "id", "");
		TbGroup obj = null;

		if (StringUtils.isNotEmpty(id)) {

			obj = tbGroupService.execFindById(id);
			if (obj != null) {
				JSONObject jobj = new JSONObject(obj);
				out.println(jobj.toString());
			}
		} else {
			out.println("");
		}

	}

	/**
	 * 删除数据
	 * @param request
	 * @param response
	 * @param out
	 */
	@RequestMapping(value = "/ser_delete", method = RequestMethod.POST)
	public void delete(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Expires", "0");
		response.setHeader("Content-Type", "text/html;charset=utf-8");
		String msg = "";
		try {
			String ids = ServletRequestUtils.getStringParameter(request, "ids", "");
			if (StringUtils.isNotEmpty(ids)) {
				String wheresql = " o.idGroup in ('" + ids + "')";
				tbGroupService.queryDeleteBatch(wheresql);
				msg = "删除成功!";
			}
		} catch (Exception e) {
			msg = "删除数据出现异常!" + e.getMessage();
		}

		out.println(msg);
	}

	/**
	 * 修改数据
	 * @param request
	 * @param response
	 * @param out
	 */
	@RequestMapping(value = "/ser_update", method = RequestMethod.POST)
	public void update(HttpServletRequest request, HttpServletResponse response, PrintWriter out, TbGroup entity) {
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Expires", "0");
		response.setHeader("Content-Type", "text/html;charset=utf-8");
		
		String id = ServletRequestUtils.getStringParameter(request, "idGroup","");
		String msg="";
		TbGroup obj=tbGroupService.execFindById(id);
		if(obj!=null){
			String groupName = ServletRequestUtils.getStringParameter(request, "groupName", "");
			if (StringUtils.isNotEmpty(groupName)) {
				obj.setGroupName(groupName);
			}			
			String groupDesc = ServletRequestUtils.getStringParameter(request, "groupDesc", "");
			if (StringUtils.isNotEmpty(groupDesc)) {
				obj.setGroupDesc(groupDesc);
			}	
			String groupType = ServletRequestUtils.getStringParameter(request, "groupType", "");
			if (StringUtils.isNotEmpty(groupType)) {
				obj.setGroupType(groupType);
			}
			tbGroupService.execUpdate(obj);
			msg="记录更新成功！";
		}else{
			msg="数据加载有异常，请确认传入的Id是否正确？";
		}
		out.println(msg);
	}
	/**
	 * 获取用户的权限系统
	 * @param request
	 * @param response
	 * @param out
	 * @param entity
	 */
	@RequestMapping(value = "/ser_getUserSystem", method = RequestMethod.GET)
	public void getUserSystem(HttpServletRequest request, HttpServletResponse response, PrintWriter out, TbGroup entity) {
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Expires", "0");
		response.setHeader("Content-Type", "text/json;charset=utf-8");
		String msg="";
		TbUser user = GetLoginSession(request, response);
	
		if (null != user) {
			List<Object[]> tbgroup=tbGroupService.getUserSystem(user);
			List jsonList=new ArrayList();
			if(tbgroup!=null){
				for(Object[] obj:tbgroup){				
					Map datamap=new HashMap();
					datamap.put("key", obj[0]);
					datamap.put("value", obj[1]);
					jsonList.add(datamap);
				}
			}
			JSONObject json = new JSONObject();

			try {
				json.put("options", jsonList);
			} catch (JSONException e) {
				e.printStackTrace();
			}			
			msg = json.toString();
		} else {
			msg = "会话过期,请点击右上角的注销重新登录.";
		}
		out.println(msg);
	}
	/**
	 * 获取用户的权限系统下的角色
	 * @param request
	 * @param response
	 * @param out
	 * @param entity
	 */
	@RequestMapping(value = "/ser_getUserRole", method = RequestMethod.GET)
	public void getUserRole(HttpServletRequest request, HttpServletResponse response, PrintWriter out, TbGroup entity) {
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Expires", "0");
		response.setHeader("Content-Type", "text/json;charset=utf-8");
		String msg="";
		String idSystem = ServletRequestUtils.getStringParameter(request, "idSystem", "");

		TbUser user = GetLoginSession(request, response);
		if (null != user) {
			List<Object[]> tbgroup=tbGroupService.getUserRole(user,idSystem);
			List jsonList=new ArrayList();
			if(tbgroup!=null){
				for(Object[] obj:tbgroup){				
					Map datamap=new HashMap();
					datamap.put("key", obj[0]);
					datamap.put("value", obj[1]);
					jsonList.add(datamap);
				}
			}
			JSONObject json = new JSONObject();

			try {
				json.put("options", jsonList);
			} catch (JSONException e) {
				e.printStackTrace();
			}			
			msg = json.toString();
		} else {
			msg = "会话过期,请点击右上角的注销重新登录.";
		}
		out.println(msg);
	}
	
	/**
	 * @description 获取组列表
	 * @param request
	 * @param response
	 * @param out
	 * @param entity
	 */
	@RequestMapping(value = "/ser_getGroupList", method = RequestMethod.GET)
	public void getGroupList(HttpServletRequest request, HttpServletResponse response, PrintWriter out, TbGroup entity) {
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Expires", "0");
		response.setHeader("Content-Type", "text/json;charset=utf-8");
		String msg="";
		TbUser user = GetLoginSession(request, response);
		if (null != user) {
			List<TbGroup> tbgroup=tbGroupService.getGroupList(user);
			List jsonList=new ArrayList();
			if(tbgroup!=null){
				for(TbGroup obj:tbgroup){				
					Map datamap=new HashMap();
					datamap.put("key", obj.getIdGroup());
					datamap.put("value", obj.getGroupName());
					jsonList.add(datamap);
				}
			}
			
			JSONObject json = new JSONObject();
			try {
				json.put("options", jsonList);
			} catch (JSONException e) {
				e.printStackTrace();
			}			
			msg = json.toString();
		} else {
			msg = "会话过期,请点击右上角的注销重新登录.";
		}
		out.println(msg);
	}
	/**
	 * @description 获取组所对应的角色
	 * @param request
	 * @param response
	 * @param out
	 * @param entity
	 */
	@RequestMapping(value = "/ser_getGroupRoles", method = RequestMethod.GET)
	public void getGroupRoles(HttpServletRequest request, HttpServletResponse response, PrintWriter out, TbGroup entity) {
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Expires", "0");
		response.setHeader("Content-Type", "text/json;charset=utf-8");
		String msg="";
		String idGroups = ServletRequestUtils.getStringParameter(request, "idGroups", "");

		if (StringUtils.isNotEmpty(idGroups)) {
			Set<TbRole> tbRole=tbGroupService.getGroupRoles(idGroups);
			List jsonList=new ArrayList();
			if(tbRole!=null){
				for(TbRole obj:tbRole){				
					Map datamap=new HashMap();
					datamap.put("key", obj.getIdRole());
					datamap.put("value", obj.getRoleName());
					jsonList.add(datamap);
				}
			}			
			JSONObject json = new JSONObject();
			try {
				json.put("options", jsonList);
			} catch (JSONException e) {
				e.printStackTrace();
			}			
			msg = json.toString();
		} else {
			msg = "请传入正确的ID";
		}
		out.println(msg);
	}
}
